//index.js
//获取应用实例
const app = getApp();
import util from '../../../utils/util';
import requestUtil from '../../../utils/requestUtil';
import _DuoguanData from '../../../utils/data';
import dg from '../../../utils/dg';
//获取应用实例
Page({

  /**
   * 页面的初始数据
   */
  data: {
    is_show: false,
    config:[],
    is_rank:false,
    is_show_rank:false,
    puid:0,
    nid:0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    if (options.id != undefined) {
      that.setData({puid:options.id});  //邀请人id
    }
    var requestData = {};
    if (that.data.puid != 0) {
      requestData.puid = that.data.puid;
    }
    if (!dg.getStorageSync('is_first_sync_user_info')) {  //用户授权 同步用户信息
      that.onSyncWechatInfo();
    }else{
      that.getIndexInfo(requestData);   //获取首页数据信息
    }
    //先隐藏分享按钮，等加载完数据后再显示分享
    if (dg.hideShareMenu) dg.showShareMenu();

    //获取分享信息
    requestUtil.get(_DuoguanData.duoguan_get_share_data_url, { mmodule: 'DuoguanWenda' }, (info) => {
      that.shareInfo = info;
      if (dg.showShareMenu) dg.showShareMenu();   //显示分享按钮
    });
  },
  
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    var nid = that.data.nid;
    var requestData = {};
    if (that.data.puid != 0) {
      requestData.puid = that.data.puid;
    }
    if (!dg.getStorageSync('is_first_sync_user_info') && nid!=0) {  //用户授权 同步用户信息
      that.onSyncWechatInfo();
    } else {
      if(nid!=0){
        that.getIndexInfo(requestData);   //获取首页数据信息
      }
    }
    that.setData({nid:nid+1});
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    var that = this;
    var requestData = {};
    that.getIndexInfo(requestData);   //获取首页数据信息
    setTimeout(() => {
      wx.stopPullDownRefresh();
    }, 1000);
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    if (res.from === 'button') {
      let is_add = res.target.dataset.key || 0;
      
      if (is_add == 1) {
        // 来自页面内转发按钮
        var path = 'pages/wenda/index/index?id=' + this.data.config.uid;
      } else {
        var path = 'pages/wenda/index/index';
      }
    } else {
      var path = 'pages/wenda/index/index';
    }

    this.shareInfo = this.shareInfo || {};
    const title = this.shareInfo.title || '全民答题，不服来战';
    const desc = this.shareInfo.desc || '';

    return {
      title: title,
      path: path,
      success: function (res) {
        // 转发成功
      },
      fail: function (res) {
        // 转发失败
      }
    }
  },

  /**
    * 获取首页信息
    */
  getIndexInfo: function (requestData) {
    var that = this;
    requestUtil.get(_DuoguanData.duoguan_host_api_url + "/index.php/addon/DuoguanWenda/ApiNew/get_info.html", requestData, (data) => {
      if (data == -1) {
        wx.showModal({
          title: '提示',
          content: '管理后台未配置赛季信息，请先前往后台配置信息。',
          success: function (res) {
            if (res.confirm) {
              console.log('用户点击确定')
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          }
        })
        return;
      }
      
      if(data.is_start==1 && data.is_end==0){
          that.setData({
            is_on:true
          })
      }else{
        that.setData({
          is_on:false
        })
      }
      if(data.my_top=='未上榜'){
        that.setData({
          is_rank:true
        })
      }else{
        that.setData({
          is_rank: false
        })
      }
    
      that.setData({
        config:data,
        is_start:data.is_start,
        is_end:data.is_end,
        is_show_rank:data.is_end
      });
      
      //倒计时 如果活动未开始，执行倒计时
      if (data.is_start == 0) {
        that.countTime();   //倒计时
      }
    }, this); // { completeAfter: dg.stopPullDownRefresh }
  },


  /**
   * 开启新赛季
   */
  StartNew:function(){
    let have_new = this.data.config.have_new;
    if(have_new==0){  //判断是否有新赛季，若没有则关闭当前窗口
      this.setData({
        is_show_rank:false
      })
    }else{      //有新赛季
      let requestData = {};
      requestData.next_active_id = this.data.config.next_active_id; //下一个赛季的活动id
      requestUtil.get(_DuoguanData.duoguan_host_api_url + "/index.php/addon/DuoguanWenda/ApiNew/get_new_info.html", requestData, (data) => {
        
        if (data.is_start == 1 && data.is_end == 0) {
          this.setData({
            is_on: true
          })
        }
        if (data.my_top == '未上榜') {
          this.setData({
            is_rank: true
          })
        }
        this.setData({
          config: data,
          is_start: data.is_start,
          is_show_rank: data.is_end
        });
        //倒计时 如果活动未开始，执行倒计时
        if (data.is_start == 0) {
          this.countTime();   //倒计时
        }
      }, this);
    }
  },

  /**
  * 同步微信信息
  */
  onSyncWechatInfo: function () {
    var that = this;
    var requestData = {};
    if (that.data.puid != 0) {
      requestData.puid = that.data.puid;
    }
    if (requestUtil.isLoading(that.syncWechatInfoId)) return;
    util.getUserInfo((info) => {
      //保存用户信息
      this.syncWechatInfoId = requestUtil.post(_DuoguanData.duoguan_user_info_post_url, {
        nickname: info.nickName,
        headimgurl: info.avatarUrl,
        sex: info.gender,
        city: info.city, province: info.province,
        country: info.country, language: info.language,
      }, (data) => {
        this.setData({ userInfo: data });
        dg.setStorageSync('is_first_sync_user_info', true);   //添加缓存
        that.getIndexInfo(requestData);   //获取首页数据信息
      });
    });
  },

  /**
    * 活动规则弹窗展示
    */
  openRule: function () {
    this.setData({
      is_show: true
    })
  },
  
  /**
   * 关闭活动规则弹窗
   */
  closeRule: function () {
    this.setData({
      is_show: false
    })
  },

  /**
   *带天数的倒计时
   */
  countTime: function () {
    //获取当前时间  
    var that = this;
    var date = new Date();
    var now = date.getTime();
    //设置截止时间  
    var endDate = new Date(that.data.config.start_time);
    var end = endDate.getTime();
    //时间差  
    var leftTime = end - now;
    //定义变量 d,h,m,s保存倒计时的时间  
    var d, h, m, s;
    if (leftTime >= 0) {
      d = Math.floor(leftTime / 1000 / 60 / 60 / 24);
      h = Math.floor(leftTime / 1000 / 60 / 60 % 24);
      m = Math.floor(leftTime / 1000 / 60 % 60);
      s = Math.floor(leftTime / 1000 % 60);
    }

    if (d == 0 && h == 0 && m == 0 && s == 0) {
      that.setData({ is_start: 1 });
      return;
    } else {
      //将倒计时赋值到时间控件中  
      that.setData({
        days: d,
        hours: h,
        minutes: m,
        seconds: s
      });
    }
    //递归每秒调用countTime方法，显示动态时间效果  
    setTimeout(that.countTime, 1000);
  },

  /**
   * 跳转到答题页面
   */
  ToAnswer: function (e) {
    let that = this;
    let user_num = that.data.config.re_num;
    let active_id = that.data.config.id;
    if (that.data.config.is_end == 0) {
      if (user_num == 0) {
        wx.showToast({
          title: '您的答题机会已用完',
          icon: 'none',
          duration: 2000
        })
      } else {
        wx.showModal({
          title: '提示',
          content: '开始答题后将使用一次机会，答题中切勿退出，确定要开始答题吗？',
          success: function (res) {
            if (res.confirm) {
              //跳转页面
              wx.redirectTo({
                url: '../answer/answer?active_id='+active_id
              });
            } else if (res.cancel) {
              console.log('用户点击取消');
            }
          }
        })
      }
    } else {
      wx.navigateTo({
        url:'../ranking/ranking?active_id='+active_id
      })
    }
  },
  /**
   * 进入排行榜
   */
  ToRanking: function () {
    let active_id = this.data.config.id;
    wx.navigateTo({
      url: '../ranking/ranking?active_id=' + active_id,
    })
  }
})
